﻿@using IotClientApp.Shared
@using IotClientApp.Shared.Enums;
@using Newtonsoft.Json;
@inject HttpClient httpClient
@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">
            <MudIcon Icon="@Icons.Material.Filled.DeleteForever" Class="mr-3 mb-n1" />
            @Title
        </MudText>
    </TitleContent>
    <DialogContent>
        <MudHidden Value="@deviceInfo.Id"></MudHidden>
        @*<MudTextField Value="@deviceInfo.Name" @bind-Value="deviceInfo.Name" Label="名称" />*@
        <MudTextField @bind-Value="deviceInfo.Name" Label="名称" />
        <MudTextField Value="@deviceInfo.Desc" Label="描述" />
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">取消</MudButton>
        <MudButton Color="Color.Success" OnClick="SaveServer">保存</MudButton>
    </DialogActions>
</MudDialog>
@code {
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }

    [Parameter] public DeviceInfoModel deviceInfo { get; set; } = new DeviceInfoModel();
    /// <summary>
    /// 标题
    /// </summary>
    [Parameter]
    public string Title { get; set; } = "新增";

    private void Cancel()
    {
        MudDialog.Cancel();
    }
    private void onchange()
    {
        Console.WriteLine();
    }
    private async Task SaveServer()
    {
        var response = await httpClient.PostAsJsonAsync("api/Device/SaveDeviceInfo", deviceInfo);
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            try
            {
                var result = JsonConvert.DeserializeObject<ApiResult<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Code == ResultCode.Success)
                    {
                        //In a real world scenario this bool would probably be a service to delete the item from api/database
                        Snackbar.Add(Title, Severity.Success);
                        MudDialog.Close(DialogResult.Ok(deviceInfo.Id));
                    }
                    else
                    {
                        Snackbar.Add(result.ErrorMsg, Severity.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        else
        {
            Snackbar.Add(Title, Severity.Error);
        }
    }
}